import csv

num = 10


# 逐行读取并检查是否为UTF-8编码
def extract_utf8_rows(file_path, output_path):
    count = 0
    with open(file_path, 'r', encoding='utf-8', errors='ignore') as infile, \
            open(output_path, 'w', encoding='utf-8', newline='') as outfile:
        reader = csv.reader(infile)
        writer = csv.writer(outfile)

        # 读取列名
        header = next(reader)
        writer.writerow(header)  # 将列名写入输出文件

        for row in reader:
            count += 1
            # 检查每一行的编码是否为UTF-8
            try:
                row_str = ','.join(row)  # 将行转换为字符串
                row_str.encode('utf-8')  # 尝试将字符串编码为UTF-8
                writer.writerow(row)  # 如果是UTF-8编码，写入输出文件
            except UnicodeEncodeError:
                # 如果不是UTF-8编码，跳过该行
                continue
            if count == num:
                break


input_csv = 'filtered_file.csv'
output_csv = 'output_utf8.csv'

extract_utf8_rows(input_csv, output_csv)
